<template>
  <slot></slot>
  <el-button
    v-if="previewShow"
    v-permissions="{ permission: ['preview:' + pageName] }"
    :disabled="previewBtnInfo.disabled"
    :readonly="previewBtnInfo.readonly"
    size="small"
    type="primary"
    @click="onHandlePreview"
  >
    预览
  </el-button>
  <el-button
    v-if="downloadShow"
    v-permissions="{ permission: ['download:' + pageName] }"
    :disabled="downloadBtnInfo.disabled"
    :readonly="downloadBtnInfo.readonly"
    size="small"
    type="primary"
    @click="onHandleDownload"
  >
    下载
  </el-button>
  <slot name="beforeDetailBtn"></slot>
  <el-button
    v-if="detailShow"
    :disabled="detailBtnInfo.disabled"
    :readonly="detailBtnInfo.readonly"
    size="small"
    type="primary"
    @click="onHandleDetail"
  >
    查看
  </el-button>
  <slot name="beforeEditBtn"></slot>
  <template v-if="editShow">
    <el-button
      v-if="!isClickEdit || (isEditByRow && !isEditByRow(row))"
      v-permissions="{ permission: ['update:' + pageName] }"
      :disabled="editBtnInfo.disabled"
      :readonly="editBtnInfo.readonly"
      size="small"
      type="primary"
      @click="onHandleEdit"
    >
      编辑
    </el-button>
    <template v-else-if="!isClickEdit || (isEditByRow && isEditByRow(row))">
      <el-button size="small" type="primary" @click="onHandleSave"> 保存 </el-button>
      <el-button size="small" type="info" @click="onHandleCancel"> 取消 </el-button>
    </template>
  </template>
  <slot name="beforeDeleteBtn"></slot>
  <el-button
    v-if="delShow"
    v-permissions="{ permission: ['del:' + pageName] }"
    :disabled="delBtnInfo.disabled"
    :readonly="delBtnInfo.readonly"
    size="small"
    type="danger"
    @click="onHandleDelete"
  >
    删除
  </el-button>
  <slot name="afterDeleteBtn"></slot>
</template>

<script>
import { operateType } from "@/plugins/commonType.enum";
import { deleteOne, downloadFile, postRequest } from "@/api/mains";
import { baseURL, previewServer } from "@/config";
import { Base64 } from "js-base64";
import { ElLoading } from "element-plus";
import { useRoute } from "vue-router";
import mitt from "mitt";
import _ from "lodash";
import { succMsg, confirm, failMsg } from "@/utils/MessageUtils";

export default defineComponent({
  name: "CommonTableOperationBtns",
  props: {
    row: {
      type: Object,
      default: () => {
        return {};
      }
    },
    rowIndex: {
      type: Number,
      default: 0
    },
    emitUrl: {
      type: String,
      default: ""
    },
    emitEditId: {
      type: String,
      default: "id"
    },
    isEditByRow: {
      type: Function,
      default: () => {}
    },
    url: {
      type: String,
      default: ""
    },
    updateUrl: {
      type: String,
      default: ""
    },
    downloadUrl: {
      type: String,
      default: "org"
    },
    detailShow: {
      type: Boolean,
      default: true
    },
    previewShow: {
      type: Boolean,
      default: false
    },
    downloadShow: {
      type: Boolean,
      default: false
    },
    isClickEdit: {
      type: Boolean,
      default: false
    },
    editShow: {
      type: Boolean,
      default: true
    },
    delShow: { type: Boolean, default: true },
    detailBtnInfo: {
      type: Object,
      default: () => {
        return {
          disabled: false,
          readonly: false
        };
      }
    },
    previewBtnInfo: {
      type: Object,
      default: () => {
        return {
          disabled: false,
          readonly: false
        };
      }
    },
    downloadBtnInfo: {
      type: Object,
      default: () => {
        return {
          disabled: false,
          readonly: false
        };
      }
    },
    editBtnInfo: {
      type: Object,
      default: () => {
        return {
          disabled: false,
          readonly: false
        };
      }
    },
    delBtnInfo: {
      type: Object,
      default: () => {
        return {
          disabled: false,
          readonly: false,
          isDel: true //默认组件内删除
        };
      }
    }
  },
  emits: {
    "handle-edit-info": null,
    "del-success": null,
    "on-success": null,
    "on-fail": null,
    "on-del-row": null
  },

  setup(props, { emit }) {
    const _emitter = mitt();

    const $pubFunc = () => {
      _emitter.emit(_.head(arguments), arguments[1]);
    };

    const route = useRoute();
    //const $pub = inject("$pub");
    const filePath = ref("");

    /**
     * 页面路由名字
     */
    const pageName = computed(() => {
      return route.name;
    });

    /**
     * 预览
     */
    const onHandlePreview = () => {
      const { row } = props;
      const { filepath: currentPath } = row || {};
      filePath.value = currentPath;
      window.open(previewServer + encodeURIComponent(Base64.encode(`${baseURL}/${filePath.value}`)));

      // type.value = onGetFileType(filename)
      // if (!type.value) {
      //   failMsg('该文件不支持预览')
      //   return
      // }
      // commonPreviewRef.value.show()
    };

    /**
     * 下载
     */
    const onHandleDownload = () => {
      const { row, downloadUrl } = props;

      const { id, filepath, filename } = row || {};
      if (id && filepath) {
        confirm("你确定要下载当前项吗", async () => {
          downloadFile(downloadUrl, { filename: filepath }).then(res => {
            const link = document.createElement("a");

            const blob = new Blob([res], {
              type: "application/octer-stream"
            });

            link.style.display = "none";

            link.href = URL.createObjectURL(blob);

            link.setAttribute("download", filename);

            document.body.appendChild(link);

            link.click();

            document.body.removeChild(link);
          });
          // succMsg(msg)
        });
      }
    };
    /**
     *  详情按钮
     */
    const onHandleDetail = async () => {
      const { row } = props;
      emit("handle-edit-info", operateType.DETAIL, row);
    };

    /**
     *  编辑按钮
     */
    const onHandleEdit = async () => {
      const { row } = props;

      if (props.isClickEdit) {
        const eventName = pageName.value + props.emitEditId; //(props.emitUrl || props.url) + 'editRow'
        $pubFunc(eventName, { row, rowIndex: props.rowIndex });
        return;
      }
      emit("handle-edit-info", operateType.EDIT, row);
    };

    /**
     * 保存当前行
     */

    const onHandleSave = async () => {
      const { row } = props;
      const url = props.updateUrl || `${props.url}/update`;
      const res = await postRequest(url, row);

      if (res.code == 200) {
        const eventName = pageName.value;
        $pubFunc(`${eventName}queryData`);
        emit("on-success", res);
      } else {
        failMsg(res.msg);
        emit("on-fail", res);
      }
    };

    /**
     * 还原当前行
     */

    const onHandleCancel = () => {
      const { row } = props;
      const eventName = `${pageName.value + props.emitEditId}cancel`; //(props.emitUrl || props.url) + 'editRow'
      $pubFunc(eventName, { row, rowIndex: props.rowIndex });
    };
    /**
     *  删除按钮
     */
    const onHandleDelete = async () => {
      const { row, url } = props;
      if (!props.delBtnInfo?.isDel || !url) {
        emit("on-del-row", row);
        return;
      }
      if (row.id) {
        confirm("你确定要删除当前项吗", async () => {
          const loading = ElLoading.service({
            lock: true,
            text: "删除中，请稍候...",
            background: "rgba(0, 0, 0, 0.7)"
          });
          const { code, msg } = await deleteOne(url, row.id);
          loading.close();
          if (code == 200) {
            succMsg(msg);
            const eventName = pageName.value;
            $pubFunc(`${eventName}queryData`);
            emit("del-success");
          }
        });
      }
    };

    return {
      pageName,
      onHandlePreview,
      onHandleDownload,
      onHandleDetail,
      onHandleEdit,
      onHandleDelete,
      onHandleSave,
      onHandleCancel
    };
  }
});
</script>
